package com.caigou.modules.channel.ui

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.channel.R
import com.caigou.modules.channel.adapter.TeamItemAdapter
import com.caigou.modules.channel.bean.TeamBean
import com.caigou.modules.channel.bean.TeamItemBean
import com.caigou.modules.channel.databinding.FragmentTeamBinding
import com.caigou.modules.channel.viewmodel.ChannelViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/10/12
 */
@AndroidEntryPoint
class TeamFragment : BaseFragment() {

    private var _binding: FragmentTeamBinding? = null
    private val binding get() = _binding!!

    private val channelViewModel: ChannelViewModel by viewModels()

    private val teamList = mutableListOf<TeamItemBean>()

    private var page = 1
    private val limit = 10
    private var totalPage = 0

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(requireActivity())
    }

    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(requireActivity())
    }

    private val mAdapter: TeamItemAdapter by lazy {
        TeamItemAdapter(teamList)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentTeamBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.teamSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                mAdapter.loadMoreModule.isEnableLoadMore = false
                page = 1
                fetchTeamList()
            }
        }

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                fetchTeamList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.getItem(position)
            ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                .withString(AppConstants.USER_ID, item.userId)
                .navigation()
        }

        binding.teamRecyclerViewList.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }

        binding.teamBtnInvite.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Tools.PAGE_TOOLS)
                .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Tools.TAG_INVITE)
                .navigation()
        }

        binding.teamTvBack.setOnClickListener {
            (requireActivity() as ChannelActivity).onBackPressed()
        }
    }

    override fun lazyLoad() {
        fetchTeamList()
    }


    override fun onBack() {
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(channelViewModel.teamListLiveData, ::handleGetTeamList)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleGetTeamList(status: Resource<TeamBean>) {
        when (status) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.teamSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(status.errorMsg)) {
                    showToast(status.errorMsg)
                } else {
                    showToast("获取团队信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.teamSwipeRefreshLayout.isRefreshing = false
                mAdapter.loadMoreModule.isEnableLoadMore = true

                if (status.data == null) {
                    return
                }
                binding.teamTvNum.text = status.data!!.totalCount.toString()
                totalPage = status.data!!.totalPage

                if (page == 1) {
                    mAdapter.setList(status.data!!.list)
                } else {
                    mAdapter.addData(status.data!!.list)
                }

                if (status.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun fetchTeamList() {
        channelViewModel.getTeamList(page, limit, AppBackgroundInfo.instance.userBean!!.userId)
    }
}